const express = require('express');
const RolesModel = require('../model/roles')
const MenuModel = require('../model/menu')
const {formatDate} = require('../utils/util')
const router = express.Router()

//查询角色信息
router.get("/findRoles",async (req,res)=>{
    try {
        const data = await RolesModel.find({state:1});
        res.send({
            code:1,
            data:data
        });
    } catch (error) {
        res.send({
            code:0,
            data:data
        });
    }
});
// 添加角色 
router.post('/addRoles',async (req,resp,next)=>{
    try {
        const {name} = req.body;
        const result = await RolesModel.insertMany({name,createTime:formatDate(),state:1})
        if (result && result.length>0) {
            resp.send({
                code: 1,
                msg: "添加成功"
            })
        } else {
            resp.send({
                code: 0,
                msg: "添加失败"
            })
        }
    } catch (error) {
        next(error);
    }
})
// 添加权限  /roles/addAuth
router.post('/addAuth',async (req,resp,next)=>{
    try {
        // id: 当前角色id , authUser 谁在授权  authTime: 授权时间   menus 选中的菜单
        const {id,authUser,authTime,menus} = req.body;
        const res = await RolesModel.updateOne({"_id":id},{authUser,authTime,menus});
        
        if(res.modifiedCount){
            resp.send({
                code: 1,
                msg:"修改成功"
            })
        }else{
            resp.send({
                code: 0,
                msg:"修改失败"
            })
        }
    } catch(err){
        next(err)
    }

})
// 删除, 假删除，只是把state设置为0
router.post('/deleteRoles',async (req,resp,next)=>{
    try {
        const {id} = req.body;
        const res = await RolesModel.deleteOne({"_id":id});
        console.log(res,'删除的数据');
        
        if(res.deletedCount){
            resp.send({
                code: 1,
                msg:"删除成功"
            })
        }else{
            resp.send({
                code: 0,
                msg:" 删除失败"
            })
        }
    } catch(err){
        next(err)
    }
   
})
// 根据角色的ID查询角色
router.post('/findRoleById', async (req,res,next)=>{
    const {roleId} = req.body;
    let data = {}
    try {
        data = await RolesModel.find({state:1,_id:roleId});
        res.send({
            code:1,
            data:data
        });
    } catch (error) {
        res.send({
            code:0,
            data:data
        });
        next(error);
    }
})


module.exports = router;